using UnityEngine;
using QFramework;
using System.Collections;
using QFramework.Example;

namespace QFramework.FlyBird
{
    public partial class Player : ViewController
    {
        private Rigidbody2D mRigidbody2D;
        public float mJumpHow = 5;
        private SpriteRenderer mSpriteRenderer;
        bool mCheckPlayerInScreen = false;
        IEnumerator Start()
        {
            mRigidbody2D = GetComponent<Rigidbody2D>();
            mSpriteRenderer = GetComponent<SpriteRenderer>();
            yield return new WaitForEndOfFrame();
            mCheckPlayerInScreen = true;
            FlappyBird.GameState.RegisterWithInitValue(state =>
            {
                if (state == GameStates.NotStart)
                {
                    mRigidbody2D.bodyType = RigidbodyType2D.Static;
                }
                else
                {
                    mRigidbody2D.bodyType = RigidbodyType2D.Dynamic;
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }
        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                if (FlappyBird.GameState.Value == GameStates.NotStart)
                {
                    FlappyBird.GameState.Value = GameStates.Started;
                }
                if (FlappyBird.GameState.Value == GameStates.Started)
                {
                    mRigidbody2D.velocity = new Vector2(mRigidbody2D.velocity.x, mJumpHow);
                    AudioKit.PlaySound("Jump");
                }
            }

            if (mRigidbody2D.velocity.y > 0)
            {
                var angleZ = Mathf.Lerp(0, 30, mRigidbody2D.velocity.y / 5);
                transform.localEulerAngles = new Vector3(0, 0, angleZ);
            }
            else
            {
                var angleZ = Mathf.Lerp(0, -30, Mathf.Abs(mRigidbody2D.velocity.y / 5) );
                transform.localEulerAngles = new Vector3(0, 0, angleZ);
            }


            if (mCheckPlayerInScreen && !mSpriteRenderer.isVisible)
            {
                GameOver();
            }
        }
        private void OnCollisionEnter2D(Collision2D collision)
        {
            GameOver();
        }
        void GameOver()
        {
            if (FlappyBird.GameState.Value == GameStates.Started)
            {
                AudioKit.PlaySound("Die");
                FlappyBird.GameState.Value = GameStates.GameOver;
            }
        }
    }
}
